#!/bin/bash
#
# Strict 15-minute Sanity Check for KWDB SDK Performance
# Goal: Verify that reported QPS is "actual points written to DB per second"
# NOT batches, NOT requests, but individual data points
#

set -e

echo "================================================"
echo "  KWDB SDK Strict Performance Sanity Check"
echo "  (15-minute validation to avoid inflated QPS)"
echo "================================================"
echo ""

# Strict test configuration - SAME for both UDS and TCP
TOTAL_RECORDS=50000    # Reduced for quick test
BATCH_SIZE=500
LINGER_MS=50
CONCURRENCY=2
MODE="stream"

# Database connection for verification
DB_HOST="${KWDB_DB_HOST:-127.0.0.1}"
DB_PORT="${KWDB_DB_PORT:-26257}"
DB_NAME="${KWDB_DB_NAME:-defaultdb}"
DB_USER="${KWDB_DB_USER:-root}"

echo "[Step 1/7] Configuration"
echo "  Total Records: $TOTAL_RECORDS"
echo "  Batch Size: $BATCH_SIZE"
echo "  Linger MS: $LINGER_MS"
echo "  Concurrency: $CONCURRENCY"
echo "  Mode: $MODE"
echo ""

# Build benchmark
echo "[Step 2/7] Building benchmark..."
cd /home/xiaodouzi/workspace/422a67685e23f903e048434351289787/build
make bench_write -j4 > /dev/null 2>&1
echo "  ✓ Build complete"
echo ""

# Start server in background with monitoring
echo "[Step 3/7] Starting ingestd server..."
killall -9 ingestd 2>/dev/null || true
sleep 1
rm -f /tmp/kwdb-ingestd.sock /tmp/ingestd_monitor.log

cd /home/xiaodouzi/workspace/422a67685e23f903e048434351289787
./build/server/ingestd/ingestd > /tmp/ingestd_monitor.log 2>&1 &
SERVER_PID=$!
sleep 3

if ! kill -0 $SERVER_PID 2>/dev/null; then
    echo "  ✗ Server failed to start!"
    cat /tmp/ingestd_monitor.log
    exit 1
fi
echo "  ✓ Server started (PID: $SERVER_PID)"
echo ""

# Function to get database row count
get_row_count() {
    psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -t -c \
        "SELECT COUNT(*) FROM bench_test_0 WHERE measurement LIKE 'bench_test_%'" 2>/dev/null | tr -d ' ' || echo "0"
}

# Clean database before test
echo "[Step 4/7] Preparing database..."
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c \
    "DROP TABLE IF EXISTS bench_test_0, bench_test_1, bench_test_2, bench_test_3" 2>/dev/null || true
echo "  ✓ Database cleaned"
echo ""

# UDS Test
echo "[Step 5/7] Running UDS benchmark..."
echo "  Transport: Unix Domain Socket"
echo "  Path: /tmp/kwdb-ingestd.sock"
echo ""

# Get initial row count
INITIAL_COUNT=$(get_row_count)
echo "  Initial row count: $INITIAL_COUNT"

# Run UDS test
UDS_START=$(date +%s)
INGEST_ENDPOINT=local ./build/bench/cpp/bench_write \
    $TOTAL_RECORDS \
    $BATCH_SIZE \
    $CONCURRENCY \
    > /tmp/uds_output.log 2>&1

UDS_END=$(date +%s)
UDS_DURATION=$((UDS_END - UDS_START))

# Wait for server to flush
sleep 2

# Get final row count
FINAL_COUNT=$(get_row_count)
UDS_ACTUAL_ROWS=$((FINAL_COUNT - INITIAL_COUNT))

# Extract metrics from output
UDS_QPS=$(grep "QPS:" /tmp/uds_output.log | awk '{print $2}')
UDS_SUCCESS=$(grep "Success:" /tmp/uds_output.log | awk '{print $2}')
UDS_DURATION_MS=$(grep "Duration:" /tmp/uds_output.log | awk '{print $2}')

echo ""
echo "  Client reported:"
echo "    - QPS: $UDS_QPS"
echo "    - Success: $UDS_SUCCESS points"
echo "    - Duration: ${UDS_DURATION_MS}s"
echo ""
echo "  Database verification:"
echo "    - Rows written: $UDS_ACTUAL_ROWS"
echo "    - Wall time: ${UDS_DURATION}s"
echo ""

# Verify consistency
if [ "$UDS_SUCCESS" != "$UDS_ACTUAL_ROWS" ]; then
    echo "  ⚠️  WARNING: Client reports $UDS_SUCCESS points but DB has $UDS_ACTUAL_ROWS rows!"
    echo "     Difference: $((UDS_SUCCESS - UDS_ACTUAL_ROWS))"
fi

# Calculate real QPS
if [ "$UDS_DURATION" -gt 0 ]; then
    UDS_REAL_QPS=$((UDS_ACTUAL_ROWS / UDS_DURATION))
    echo "  Real QPS (from DB): $UDS_REAL_QPS points/sec"
else
    UDS_REAL_QPS=0
fi
echo ""

# Clean database for TCP test
echo "[Step 6/7] Preparing for TCP test..."
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c \
    "DROP TABLE IF EXISTS bench_test_0, bench_test_1, bench_test_2, bench_test_3" 2>/dev/null || true
sleep 1

INITIAL_COUNT=$(get_row_count)
echo "  Initial row count: $INITIAL_COUNT"
echo ""

# TCP Test
echo "Running TCP benchmark..."
echo "  Transport: TCP"
echo "  Address: 127.0.0.1:9090"
echo ""

# Run TCP test
TCP_START=$(date +%s)
INGEST_ENDPOINT=127.0.0.1:9090 ./build/bench/cpp/bench_write \
    $TOTAL_RECORDS \
    $BATCH_SIZE \
    $CONCURRENCY \
    > /tmp/tcp_output.log 2>&1

TCP_END=$(date +%s)
TCP_DURATION=$((TCP_END - TCP_START))

# Wait for server to flush
sleep 2

# Get final row count
FINAL_COUNT=$(get_row_count)
TCP_ACTUAL_ROWS=$((FINAL_COUNT - INITIAL_COUNT))

# Extract metrics from output
TCP_QPS=$(grep "QPS:" /tmp/tcp_output.log | awk '{print $2}')
TCP_SUCCESS=$(grep "Success:" /tmp/tcp_output.log | awk '{print $2}')
TCP_DURATION_MS=$(grep "Duration:" /tmp/tcp_output.log | awk '{print $2}')

echo ""
echo "  Client reported:"
echo "    - QPS: $TCP_QPS"
echo "    - Success: $TCP_SUCCESS points"
echo "    - Duration: ${TCP_DURATION_MS}s"
echo ""
echo "  Database verification:"
echo "    - Rows written: $TCP_ACTUAL_ROWS"
echo "    - Wall time: ${TCP_DURATION}s"
echo ""

# Verify consistency
if [ "$TCP_SUCCESS" != "$TCP_ACTUAL_ROWS" ]; then
    echo "  ⚠️  WARNING: Client reports $TCP_SUCCESS points but DB has $TCP_ACTUAL_ROWS rows!"
    echo "     Difference: $((TCP_SUCCESS - TCP_ACTUAL_ROWS))"
fi

# Calculate real QPS
if [ "$TCP_DURATION" -gt 0 ]; then
    TCP_REAL_QPS=$((TCP_ACTUAL_ROWS / TCP_DURATION))
    echo "  Real QPS (from DB): $TCP_REAL_QPS points/sec"
else
    TCP_REAL_QPS=0
fi
echo ""

# Stop server
kill $SERVER_PID 2>/dev/null || true
sleep 1

# Analysis
echo "[Step 7/7] Sanity Check Analysis"
echo "================================================"
echo ""
echo "Configuration Consistency:"
echo "  ✓ Same total records: $TOTAL_RECORDS"
echo "  ✓ Same batch size: $BATCH_SIZE"
echo "  ✓ Same linger time: $LINGER_MS"
echo "  ✓ Same concurrency: $CONCURRENCY"
echo "  ✓ Same mode: $MODE"
echo ""

echo "Counting Method Verification:"
echo "  UDS:"
echo "    - Client counted: $UDS_SUCCESS points"
echo "    - DB contains: $UDS_ACTUAL_ROWS rows"
if [ "$UDS_SUCCESS" = "$UDS_ACTUAL_ROWS" ]; then
    echo "    ✓ PASS: Counts match"
else
    DIFF=$((UDS_SUCCESS - UDS_ACTUAL_ROWS))
    PERCENT=$((DIFF * 100 / UDS_SUCCESS))
    echo "    ✗ FAIL: Mismatch of $DIFF points ($PERCENT%)"
fi
echo ""
echo "  TCP:"
echo "    - Client counted: $TCP_SUCCESS points"
echo "    - DB contains: $TCP_ACTUAL_ROWS rows"
if [ "$TCP_SUCCESS" = "$TCP_ACTUAL_ROWS" ]; then
    echo "    ✓ PASS: Counts match"
else
    DIFF=$((TCP_SUCCESS - TCP_ACTUAL_ROWS))
    PERCENT=$((DIFF * 100 / TCP_SUCCESS))
    echo "    ✗ FAIL: Mismatch of $DIFF points ($PERCENT%)"
fi
echo ""

echo "Performance Comparison:"
echo "  UDS (Unix Domain Socket):"
echo "    - Client QPS: $UDS_QPS"
echo "    - Real QPS: $UDS_REAL_QPS (verified from DB)"
echo ""
echo "  TCP (Loopback):"
echo "    - Client QPS: $TCP_QPS"
echo "    - Real QPS: $TCP_REAL_QPS (verified from DB)"
echo ""

# Calculate ratio
if [ "$TCP_REAL_QPS" -gt 0 ] && [ "$UDS_REAL_QPS" -gt 0 ]; then
    RATIO=$(echo "scale=2; $UDS_REAL_QPS / $TCP_REAL_QPS" | bc)
    echo "  UDS/TCP Ratio: ${RATIO}x"
    echo ""

    # Check if ratio is reasonable (1.2x - 3x is normal)
    if (( $(echo "$RATIO > 10" | bc -l) )); then
        echo "  ⚠️  WARNING: Ratio ${RATIO}x is suspiciously high!"
        echo "     Normal UDS advantage is 1.2x-3x for local connections"
        echo "     Possible issues:"
        echo "       - Different code paths (one using streaming, other not)"
        echo "       - Counting batches instead of points"
        echo "       - TCP client not using localhost properly"
    elif (( $(echo "$RATIO < 1.1" | bc -l) )); then
        echo "  ⚠️  WARNING: Ratio ${RATIO}x is too small!"
        echo "     UDS should be faster than TCP for local connections"
    else
        echo "  ✓ Ratio is reasonable for UDS vs TCP"
    fi
fi
echo ""

echo "Server-side Verification:"
echo "  Check server log for actual INSERT/COPY activity:"
tail -20 /tmp/ingestd_monitor.log | grep -E "(INSERT|COPY|WriteStream|points/sec)" || echo "  No detailed server metrics found"
echo ""

echo "Summary:"
echo "  - Data consistency: $([ "$UDS_SUCCESS" = "$UDS_ACTUAL_ROWS" ] && [ "$TCP_SUCCESS" = "$TCP_ACTUAL_ROWS" ] && echo "✓ PASS" || echo "✗ FAIL")"
echo "  - Performance ratio: ${RATIO}x (UDS/TCP)"
echo "  - Total test time: ~$((UDS_DURATION + TCP_DURATION)) seconds"
echo ""
echo "Detailed logs:"
echo "  - UDS output: /tmp/uds_output.log"
echo "  - TCP output: /tmp/tcp_output.log"
echo "  - Server log: /tmp/ingestd_monitor.log"
echo "================================================"
